﻿namespace ApiLib.Utils;

/// <summary>
/// MaxKb工具类
/// </summary>
public class MaxKbUtil
{
    private readonly string _host;
    private readonly string _key;
    private readonly Dictionary<string, string> _headers = new();
    private readonly string _applicationId;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="host"></param>
    /// <param name="applicationId"></param>
    /// <param name="key"></param>
    public MaxKbUtil(string host, string applicationId, string key)
    {
        if (host.EndsWith("/"))
        {
            host = host.Substring(0, host.Length - 1);
        }

        this._host = host;
        this._key = key;
        _headers["AUTHORIZATION"] = this._key;
        this._applicationId = applicationId;
    }

    /// <summary>
    /// 获取应用相关信息
    /// </summary>
    /// <returns></returns>
    public async Task<MaxKbResponse<MaxKbProfile>?> Profile()
    {
        var url = $"{this._host}/api/application/profile";
        return await HttpUtil.HttpGetAsync<MaxKbResponse<MaxKbProfile>>(url, _headers);
    }

    /// <summary>
    /// 获取应用id对应的会话id
    /// </summary>
    /// <returns></returns>
    public async Task<MaxKbResponse<string>?> ChatOpen()
    {
        var url = $"{this._host}/api/application/{this._applicationId}/chat/open";
        return await HttpUtil.HttpGetAsync<MaxKbResponse<string>>(url, _headers);
    }

    /// <summary>
    /// 对话
    /// </summary>
    /// <returns></returns>
    public async Task<MaxKbResponse<MaxKbAnswer>?> ChatMessage(string chatId, string message)
    {
        var request = new
        {
            message = message,
            re_chat = false,
            stream = false
        };
        return await SendChatMessage(chatId, request);
    }

    /// <summary>
    /// 对话
    /// </summary>
    /// <returns></returns>
    public async Task<MaxKbResponse<MaxKbAnswer>?> ChatMessage(string chatId, MaxKbRequest request)
    {
        return await SendChatMessage(chatId, request);
    }

    private async Task<MaxKbResponse<MaxKbAnswer>?> SendChatMessage(string chatId, object request)
    {
        var url = $"{this._host}/api/application/chat_message/{chatId}";
        var start = DateTime.Now;
        var res = await HttpUtil.HttpPostAsync<MaxKbResponse<MaxKbAnswer>>(url, _headers, request);

        Console.WriteLine("AI调用耗时：" + (DateTime.Now - start).TotalMilliseconds);
        if (res is { code: 500 })
        {
            Console.WriteLine("AI调用异常：" + res?.message ?? "出现异常");
        }

        return res;
    }
}

/// <summary>
/// 基本返回
/// </summary>
/// <typeparam name="T"></typeparam>
public class MaxKbResponse<T>
{
    /// <summary>
    /// 状态码，成功：200
    /// </summary>
    public int code { get; set; }

    /// <summary>
    /// 消息，成功返回：成功
    /// </summary>
    public string message { get; set; }

    /// <summary>
    /// 数据
    /// </summary>
    public T data { get; set; }
}

/// <summary>
/// 应用相关信息
/// <code>
/// {
///   "id": "704f01ac-02f8-11f0-8d1b-0242ac110002",
///   "name": "my-ai",
///   "desc": "",
///   "prologue": "您好，我是 橙逸 小助手，您可以向我提出 工作中的 问题。\n- 公司主要业务有什么？\n- 技术支撑找谁？",
///   "dialogue_number": 1,
///   "icon": "/ui/favicon.ico",
///   "type": "SIMPLE",
///   "stt_model_id": null,
///   "tts_model_id": null,
///   "stt_model_enable": false,
///   "tts_model_enable": false,
///   "tts_type": "BROWSER",
///   "tts_autoplay": false,
///   "stt_autosend": false,
///   "file_upload_enable": false,
///   "file_upload_setting": {},
///   "work_flow": {},
///   "show_source": false,
///   "language": null,
///   "multiple_rounds_dialogue": true
/// }
///</code>
/// </summary>
public class MaxKbProfile
{
    public string id { get; set; }
    public string name { get; set; }
    public string desc { get; set; }
    public string prologue { get; set; }
    public int dialogue_number { get; set; }
    public string icon { get; set; }
    public string type { get; set; }
    public string stt_model_id { get; set; }
    public string tts_model_id { get; set; }
    public bool stt_model_enable { get; set; }
    public bool tts_model_enable { get; set; }
    public string tts_type { get; set; }
    public bool tts_autoplay { get; set; }
    public bool stt_autosend { get; set; }
    public bool file_upload_enable { get; set; }
    public Dictionary<string, object> file_upload_setting { get; set; }
    public Dictionary<string, object> work_flow { get; set; }
    public bool show_source { get; set; }
    public string language { get; set; }
    public bool multiple_rounds_dialogue { get; set; }
}

/// <summary>
/// 回答
/// </summary>
public class MaxKbAnswer
{
    public string chat_id { get; set; }
    public string id { get; set; }
    public bool operate { get; set; }

    /// <summary>
    /// 回答内容
    /// </summary>
    public string content { get; set; }

    public bool is_end { get; set; }

    /// <summary>
    /// 思考内容
    /// </summary>
    public string reasoning_content { get; set; }

    public List<MaxKbAnswerIteem> answer_list { get; set; }
    public int completion_tokens { get; set; }
    public int prompt_tokens { get; set; }
}

public class MaxKbAnswerIteem
{
    public string content { get; set; }
    public string reasoning_content { get; set; }
}

/// <summary>
/// 发送请求
/// </summary>
public class MaxKbRequest
{
    /// <summary>
    /// 问题
    /// </summary>
    public string message { get; set; }

    /// <summary>
    /// 重新生成，默认false
    /// </summary>
    public bool re_chat { get; set; }

    /// <summary>
    /// 是否流式输出，默认true
    /// </summary>
    public bool stream { get; set; }

    /// <summary>
    /// 表单数据
    /// </summary>
    public Dictionary<string, object> form_data { get; set; }

    /// <summary>
    /// 图片列表
    /// </summary>
    public List<MaxKbRequestFile> image_list { get; set; }

    /// <summary>
    /// 文档列表
    /// </summary>
    public List<MaxKbRequestFile> document_list { get; set; }

    /// <summary>
    /// 音频列表
    /// </summary>
    public List<MaxKbRequestFile> audio_list { get; set; }

    /// <summary>
    /// 运行时节点 ID
    /// </summary>
    public string runtime_node_id { get; set; }

    /// <summary>
    /// 节点数据
    /// </summary>
    public Dictionary<string, object> node_data { get; set; }

    /// <summary>
    /// 对话记录 ID
    /// </summary>
    public string chat_record_id { get; set; }

    /// <summary>
    /// 子节点数据
    /// </summary>
    public Dictionary<string, object> child_node { get; set; }
}

/// <summary>
/// 附件
/// </summary>
public class MaxKbRequestFile
{
    /// <summary>
    /// 名称
    /// </summary>
    public string name { get; set; }

    /// <summary>
    /// 地址
    /// </summary>
    public string url { get; set; }

    public string file_id { get; set; }
}